//
//  FileListView.swift
//  Browser
//
//  Created by Garenge on 2021/7/20.
//

import UIKit
import MJRefresh

class FileListView: UIView {

    private var currentPath: String = ""

    var itemClickedClosure:((_: Int, _: FileListViewCell) -> ())?

    var dataRefreshClosure:((_: FileListView?) -> ())?

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = KDefine.Color.white
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private var dataList: [FileListModel] = []
    func setData(list: [FileListModel], dirPath: String) {
        self.dataList.removeAll()
        self.dataList.append(contentsOf: list)
        self.currentPath = dirPath
        self.collectionView.reloadData()
    }

    var identifier = "FileListViewCell"

    let sideMargin: CGFloat = 5
    func getItemWidth(wholeWidth: CGFloat) -> CGFloat {
        // cell的排布, 想让cell的宽度逐渐增大, 大到一定程度, 加一个cell, 以此往复

        // 这一行至少可以放几个
        var suggestCount = 3;
        var sugWidth: CGFloat = 150;

        if wholeWidth < 420 {
            sugWidth = 110 // 3
            suggestCount = 3
        } else {

#if TARGET_OS_MACCATALYST
            sugWidth = 180;
#else
            if wholeWidth < 680 {
                sugWidth = 135 // 4
            } else if wholeWidth < 1000 {
                sugWidth = 160 // 5
            } else {
                sugWidth = 200
            }
#endif

            suggestCount = Int(floorf(Float(wholeWidth / sugWidth)));
        }
        let itemWidth = (wholeWidth - CGFloat(suggestCount - 1) * 2 * sideMargin) / CGFloat(suggestCount) - 1;
        return itemWidth;
    }

    func getItemHeight(wholeWidth: CGFloat) -> CGFloat {
        return self.getItemWidth(wholeWidth: wholeWidth) + CGFloat(70)
    }

    func getItemSize(wholeWidth: CGFloat) -> CGSize {
        return CGSize(width: self.getItemWidth(wholeWidth: wholeWidth), height: self.getItemHeight(wholeWidth: wholeWidth))
    }

    lazy var collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.getItemSize(wholeWidth: KDefine.Frame.screenWidth() - 20)
        layout.sectionInset = UIEdgeInsets(top: 2 * sideMargin, left: 2 * sideMargin, bottom: 2 * sideMargin, right: 2 * sideMargin)
        layout.minimumLineSpacing = 2 * sideMargin
        layout.minimumInteritemSpacing = 2 * sideMargin
        layout.scrollDirection = .vertical

        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = KDefine.Color.white
        collectionView.register(FileListViewCell.self, forCellWithReuseIdentifier: identifier)
        collectionView.delegate = self
        collectionView.dataSource = self
        self.addSubview(collectionView)

        collectionView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }

        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            self?.dataRefreshClosure?(self)

            collectionView.mj_header?.endRefreshing()
        })

        return collectionView
    }()

}

extension FileListView: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: FileListViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! FileListViewCell
        cell.filePathClosure = { (fileName) -> String in
            return self.currentPath + "/" + fileName
        }
        cell.fileModel = self.dataList[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        collectionView.deselectItem(at: indexPath, animated: true)

        self.itemClickedClosure?(indexPath.item, collectionView.cellForItem(at: indexPath) as! FileListViewCell)
    }
}
